//
//  OAuthViewController.swift
//  iOS07-Weibo-LPK
//
//  Created by 罗培克 on 6/26/15.
//  Copyright © 2015 lpk. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {

    // 0. 常量
    private let WB_Client_ID = "3009011465"
    private let WB_Redirect_URI = "http://www.baidu.com"
    private let WB_App_Secret = "1afc3a7eb29ce3e4386c4ae87e6b0ea6"
    
    // 1. webView
    lazy var webView: UIWebView? = {
        let web = UIWebView()
        web.delegate = self
        return web
    }()
    
    override func loadView() {
        view = webView
        
        title = "新浪微博授权"
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    /// 关闭授权页面
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadOAuthPage()
    }
    
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"
        
        webView?.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString!
        
        // 如果不是回调的 URL, 继续加载
        if !urlString.hasPrefix(WB_Redirect_URI) {
            return true
        }
        
        // 如果是回调 URL, 需要根据 URL 内容,判断是否有授权码
        let query = request.URL!.query!
        let codeStr = "code="
        if query.hasPrefix(codeStr) {
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            print("授权码\(code)")
            
            loadAccessToken(code)
        } else {
            print("用户取消授权")
            close()
        }
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    /// 使用授权码加载 token
    private func loadAccessToken(code: String) {
        // 1. urlString SSL 1.2
        let urlString = "oauth2/access_token"
        // 2. 请求参数
        let params = ["client_id": WB_Client_ID,
            "client_secret": WB_App_Secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WB_Redirect_URI]
        // 3. POST 请求
        NetworkTools.sharedNetworkTools().POST(urlString, parameters: params, success: { (_, json) -> Void in
            
            // 加载用户信息
            UserAccount(dict: json as! [String: AnyObject]).loadUserInfo({ (account, error) -> () in
                if account != nil {
                    sharedUserAccount = account
                    
                    // 切换控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(LPKSwitchRootVCNotification, object: false)
                    
                    self.close()
                    return
                }
                
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            })
            
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
        }
    }
    
    deinit {
        print("I'm gone!---OAuthController")
    }

}
